package org.videopractice.network.codec;

import org.videopractice.common.Logger;
import org.videopractice.common.StringUtils;

import io.netty.buffer.ByteBuf;

import java.io.UnsupportedEncodingException;


/**
 * 报文编、解码工具类
 */
public class MessageUtils {

	private final static String DEFAULT_CHARSET = "UTF-8";

	/**
	 * 读指定长度的内容
	 * @param buf
	 * @param length
	 * @return
	 */
	public static String readUTF8(ByteBuf buf, int length) {
		byte[] content = new byte[length];
		buf.readBytes(content);
		try {
			return new String(content, DEFAULT_CHARSET);
		} catch (UnsupportedEncodingException e) {
			Logger.e("读报文消息失败:" + e.toString());
			return "";
		}

	}

	/**
	 * 读取内容,格式按：内容长度 + 内容
	 * @param buf
	 * @return
	 */
	public static String readUTF8ByLength(ByteBuf buf) {
		int strSize = buf.readInt();
		if(strSize <= 0) {
			return "";
		}
		return readUTF8(buf, strSize);
	}

	/**
	 * 写内容(不带内容长度)
	 * @param buf
	 * @param message
	 */
	public static void writeUTF8(ByteBuf buf, String message) {
		byte[] content ;
		try {
			if(StringUtils.isNotEmpty(message)) {
				content = message.getBytes(DEFAULT_CHARSET);
				buf.writeBytes(content);
			}
		} catch (UnsupportedEncodingException e) {
			Logger.e("写报文消息失败:" + e.toString());
		}
	}

	/**
	 * 写内容(带内容长度)
	 * @param buf
	 * @param message
	 */
	public static void writeUTF8ByLength(ByteBuf buf, String message) {
		byte[] content ;
		try {
			if(StringUtils.isNotEmpty(message)) {
				content = message.getBytes(DEFAULT_CHARSET);
				buf.writeInt(content.length);
				buf.writeBytes(content);
			} else {
				buf.writeInt(0);
			}
		} catch (UnsupportedEncodingException e) {
			Logger.e("写报文消息失败:" + e.toString());
		}
	}
}
